//
//  PostingViewController.m
//  唧歪
//
//  Created by ZC on 15/7/8.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "PostingViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "AppDelegate.h"
#import "ViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ImageCompression.h"

#define postURL @"https://app.jiwaipro.com:8888/index.php/JiWai/post"
#define integralURL  @"https://app.jiwaipro.com:8888/index.php/JiWai/postuser"
#define updatimageURL @"https://app.jiwaipro.com:8888/index.php/JiWai/updatsomeimage"
#define audioURL @"https://app.jiwaipro.com:8888/index.php/JiWai/uploadaudio"
#define postIdURL @"https://app.jiwaipro.com:8888/index.php/JiWai/postId"
#define buyTimeURL @"https://app.jiwaipro.com:8888/index.php/JiWai/buyTime"

@interface PostingViewController (){
    int keyboard;
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *Placemark;
    NSDictionary *locationArray;
    AppDelegate *app;
    NSString *poststring;
    NSString *message_ID;
    NSString *currentTime;
    NSString *audiopath;
    NSString *integral;  //积分
    NSString *integralStr;
    NSURL *tmpFile;
    NSString *filePath;
    NSString *timeStr;
    NSString *more;
    UIImage *img;
    NSMutableArray *imgArray;
    UILabel *label;
    int imageX;
    NSMutableArray *capturedImages;
}
@end

@implementation PostingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    imageX = 0.0 ;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"postingBJ.jpg"]];
    self.recordView.backgroundColor = [UIColor redColor];
    self.recordView = [[FXRecordArcView alloc] initWithFrame:CGRectMake(0, 120, [UIScreen mainScreen].bounds.size.width, 320)];
    self.recordView.delegate = self;
    self.recordView.hidden = YES;
    self.navigationItem.title=@"发帖子";
    app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    self.imageArray = [NSMutableArray array];
    imgArray = [NSMutableArray array];
    capturedImages = [NSMutableArray array];
    [self.speak addTarget:self action:@selector(btnDown) forControlEvents:UIControlEventTouchDown];
    [self.speak addTarget:self action:@selector(LongPress) forControlEvents:UIControlEventTouchUpInside];
    [self.speak.layer setMasksToBounds:YES];
    [self.speak.layer setCornerRadius:7.0];
    self.navigationItem.hidesBackButton=YES;
    
    //创建右边菜单按钮
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(FaSongClick)];
    self.navigationItem.rightBarButtonItem = item;

    //创建左边菜单
    UIBarButtonItem *leftitem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(QuXiaoClick)];

    self.navigationItem.leftBarButtonItem = leftitem;
    
    //默认显示时长为5分钟
    self.minutes.text = @"60";
    
    self.minutes.delegate = self;
    //return键改成Done键
    self.minutes.returnKeyType =UIReturnKeyDone;
    
    
    [self.minutesSider addTarget:self action:@selector(change) forControlEvents:UIControlEventValueChanged];
    //为slider添加方法当slider的值改变时就会触发change方法
    self.minutesSider.continuous = NO;
    //创建定位管理器
    locationManager = [[CLLocationManager alloc] init];
    geocoder=[[CLGeocoder alloc]init];
    //设置返回全部信息
    [locationManager setDistanceFilter:kCLDistanceFilterNone];
    //设置定位精度
    [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    locationManager.delegate=self;
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
    {
        //设置定位权限 仅ios8有意义
        [locationManager requestWhenInUseAuthorization];// 前台定位
        
        //  [locationManager requestAlwaysAuthorization];// 前后台同时定位
    }
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
        //开始定位
        [locationManager startUpdatingLocation];
        app.Existence = @"0";
    }
    //键盘通知
    [[ NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeContentViewPoint:)name: UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, ([UIScreen mainScreen].bounds.size.width-20)/3)];
    self.scroll = scroll;
    [self.view addSubview:scroll];
    
    UITextView *text = [[UITextView alloc] initWithFrame:CGRectMake(0, 90, [UIScreen mainScreen].bounds.size.width, 60)];
    text.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:15];
    [text becomeFirstResponder];
    self.inputText = text;
    [self.view addSubview:text];
    self.inputText.delegate = self;
    CGFloat R  = (CGFloat) 255/255.0;
    CGFloat G = (CGFloat) 255/255.0;
    CGFloat B = (CGFloat) 255/255.0;
    CGFloat alpha = (CGFloat) 0;
    UIColor *myColorRGB = [ UIColor colorWithRed: R  green: G  blue: B  alpha: alpha ];
    self.inputText.backgroundColor = myColorRGB;
    
    label = [[UILabel alloc]initWithFrame:CGRectMake(3, 3, 200, 30)];
    label.enabled = NO;
    label.text = @"说点什么吧...";
    label.font =  [UIFont systemFontOfSize:15];
    label.textColor = [UIColor lightGrayColor];
    [self.inputText addSubview:label];
    
    
    //在弹出的键盘上面加一个view来放置退出键盘的Done按钮
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
//    topView.barTintColor = [UIColor colorWithRed:251/255.0 green:199/255.0 blue:31/255.0 alpha:1];
    [topView setBarStyle:UIBarStyleDefault];
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    doneButton.tintColor = [UIColor colorWithRed:251/255.0 green:199/255.0 blue:31/255.0 alpha:1];
    UIBarButtonItem * CameraButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"相机.png"] style:UIBarButtonItemStylePlain target:self action:@selector(cameraClick)];
    CameraButton.tintColor = [UIColor colorWithRed:251/255.0 green:199/255.0 blue:31/255.0 alpha:1];
    UIBarButtonItem * VoiceButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"语音.png"] style:UIBarButtonItemStylePlain target:self action:@selector(VoiceClick)];
    VoiceButton.tintColor = [UIColor colorWithRed:251/255.0 green:199/255.0 blue:31/255.0 alpha:1];
    NSArray * buttonsArray = [NSArray arrayWithObjects:CameraButton,VoiceButton,btnSpace,doneButton, nil];
    [topView setItems:buttonsArray];
    
    [text setInputAccessoryView:topView];
    
    self.tag = 0;
    
}

#pragma mark - 点击换行完成编辑
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (self.minutes == textField) {
        [self.minutes resignFirstResponder];
    }
    return YES;
    
}

#pragma mark -  关闭键盘
-(void) dismissKeyBoard{
    [self.inputText resignFirstResponder];
}

- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] == 0) {
        [label setHidden:NO];
    }else{
        [label setHidden:YES];
    }
    
    [textView flashScrollIndicators];   // 闪动滚动条
    
    static CGFloat maxHeight = 130.0f;
    CGRect frame = textView.frame;
    CGSize constraintSize = CGSizeMake(frame.size.width, MAXFLOAT);
    CGSize size = [textView sizeThatFits:constraintSize];
    if (size.height >= maxHeight)
    {
        size.height = maxHeight;
        textView.scrollEnabled = YES;   // 允许滚动
    }
    else
    {
        textView.scrollEnabled = NO;    // 不允许滚动，当textview的大小足以容纳它的text的时候，需要设置scrollEnabed为NO，否则会出现光标乱滚动的情况
    }
    textView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, size.height);
    
    if (textView.contentSize.height < 130) {
        self.scroll.frame = CGRectMake(0, textView.contentSize.height+90+30, [UIScreen mainScreen].bounds.size.width, 100);
    }else{
        self.scroll.frame = CGRectMake(0, maxHeight+90+30, [UIScreen mainScreen].bounds.size.width, 100);
    }
    
    
}
#pragma mark - 购买时间
-(void)timePath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        poststring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshDatatime:) withObject:poststring waitUntilDone:YES];
    }];
}

-(void)refreshDatatime:(NSString *)sender{
}

#pragma mark - 当进度条发生变化时
-(void)change{
    NSString *a = [NSString stringWithFormat:@"%f",self.minutesSider.value*120];
    self.minutes.text =[NSString stringWithFormat:@"%d",[a intValue]];
}
-(void)btnDown
{
    [self.recordView startForFilePath:[self fullPathAtCache:@"record.wav"]];

}
- (NSString *)fullPathAtCache:(NSString *)fileName{
    NSError *error;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (YES != [fm fileExistsAtPath:path]) {
        if (YES != [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
            NSLog(@"create dir path=%@, error=%@", path, error);
        }
    }
    return [path stringByAppendingPathComponent:fileName];
}
- (void)recordArcView:(FXRecordArcView *)arcView voiceRecorded:(NSString *)recordPath length:(float)recordLength{
    
}


-(void)LongPress{
    [self.recordView commitRecording];
    NSURL *recordUrl = [NSURL URLWithString:[NSTemporaryDirectory() stringByAppendingString:@"record.wav"]];
    urlPlay = recordUrl;
}
-(void)playRecordSound{
    self.avPlay = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self fullPathAtCache:@"record.wav"]] error:nil];
    [self.avPlay play];
;
}

-(void)cancelItem{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取当前时间
-(void)getTime{
    NSDateFormatter *fomatter=[[NSDateFormatter alloc]init];
    [fomatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowTime=[fomatter stringFromDate:[NSDate date]];
    currentTime=nowTime;
}

#pragma mark - 判断tag值
-(void)tagJudge{
        if(self.tag==2){
            self.tag=2;
        }else if(self.imageArray.count>0&&self.inputText.text.length==0){
            self.tag=1;
        }else{
            self.tag=0;
        }
}

#pragma mark - 积分兑换时间判断
-(void)integralBuyTime{
    int counttime = [app.jf intValue]-[more intValue];
    NSString *moreStr = [NSString stringWithFormat:@"user_id=%@&counttime=%d",app.user_id,counttime];
    [self timePath:buyTimeURL Str:moreStr];
    
}

#pragma mark - 发送按钮事件
-(void)submit{
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
    }else{
        app.Existence = @"0";
    if ([self.minutes.text intValue] > 120) {
        more = [NSString stringWithFormat:@"%d",[self.minutes.text intValue] - 120];
        if ([more intValue]> [app.jf intValue]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示:" message:@"您的积分不够" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            self.minutes.text = @"120";
        }else{
            [self fs];
            NSString *jifen = [NSString stringWithFormat:@"已扣除%@积分",more];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示:" message:jifen delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
       }
    }else{
        [self fs];
    }
    }
}
-(void)fs{
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    [self postIDPath:postIdURL Str:poststr];
    //获取当前时间
    [self getTime];
    //判断tag类型
    [self tagJudge];
    //判断内容是否满足十个字
    if (self.tag == 2) {
        NSString *poststr =[NSString stringWithFormat:@"user_id=%@&message_content=%@&message_time=%@&message_longitude=%f&message_latitude=%f&message_showtime=%@&message_tag=%d",app.user_id,self.inputText.text,currentTime,_longitude,_latitude,self.minutes.text,self.tag];
        [self londingPath:postURL Str:poststr];
        [self integralBuyTime];
    }else if(self.tag == 1){
        NSString *poststr =[NSString stringWithFormat:@"user_id=%@&message_content=%@&message_time=%@&message_longitude=%f&message_latitude=%f&message_showtime=%@&message_tag=%d",app.user_id,self.inputText.text,currentTime,_longitude,_latitude,self.minutes.text,self.tag];
        [self londingPath:postURL Str:poststr];
        [self integralBuyTime];
    }else{
        if (self.inputText.text.length < 10) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入至少十个字的内容" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }else{
            NSString *poststr =[NSString stringWithFormat:@"user_id=%@&message_content=%@&message_time=%@&message_longitude=%f&message_latitude=%f&message_showtime=%@&message_tag=%d",app.user_id,self.inputText.text,currentTime,_longitude,_latitude,self.minutes.text,self.tag];
            [self londingPath:postURL Str:poststr];
            [self integralBuyTime];
        }
    }
}
-(void)postIDPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        poststring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(postid:) withObject:poststring waitUntilDone:YES];
    }];
}
- (void)postid:(NSString *)sender{
    
}
#pragma mark - 点击发送后请求数据
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        poststring = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:poststring waitUntilDone:YES];
    }];
}
- (void)refreshData:(NSString *)sender{
    if ([sender isEqualToString:@"0"]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"帖子发表失败，请重新发送！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"是", nil];
        [alert show];
    }else{
        if (self.tag == 2) {
            [self audioupload];
        }
        if (self.imageArray.count == 0) {
        }else{
            message_ID = poststring;
            [self Imageupload];
        }
        // 帖子发表成功之后 积分数 ＋5
        NSString *poststr1 =[NSString stringWithFormat:@"user_id=%@",app.user_id];
        //发表成功之后积分请求数据
        [self londingPath2:integralURL Str2:poststr1];
        
        //帖子发表成功之后跳转到首页
        ViewController *VC=[self.storyboard instantiateViewControllerWithIdentifier:@"homeVC"];
        [self.navigationController pushViewController:VC animated:YES];
    }
}

#pragma mark - 发表成功之后积分数＋5后上传
-(void)londingPath2:(NSString *)path Str2:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        integralStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshDataInt:) withObject:integralStr waitUntilDone:YES];
    }];
}

-(void)refreshDataInt:(NSMutableArray *)senderInt{
}

-(void)audioupload{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:[self fullPathAtCache:@"record.wav"]]];
    NSURL *url = [[NSURL alloc]initWithString:audioURL];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request addData:data withFileName:@"record.wav" andContentType:@"audio/wav" forKey:@"audio_path"];
    //添加普通的请求参数
    NSString *audioTime = [NSString stringWithFormat:@"%.0f",self.recordView.recordTime];
    [request setPostValue:audioTime forKey:@"audio_time"];
    [request setPostValue:poststring forKey:@"message_id"];
    [request setDelegate:self];
    [request startAsynchronous];
}
-(void)Imageupload{
    for(int i=0; i<self.imageArray.count; i++) {
        [self SaveImage:self.imageArray[i]];
    }
}
- (void)SaveImage:(UIImage *)image{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    [UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *Image=[UIImage imageWithContentsOfFile:imageFilePath];//写入文件
    NSData *data = UIImageJPEGRepresentation(Image, 0.5);
    NSURL *url=[NSURL URLWithString:updatimageURL];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.delegate = self;
    [request setData:data  withFileName:@"tmp.jpg" andContentType:@"image/jpg" forKey:@"image_path"];
    [request setPostValue:message_ID forKey:@"message_id"];
    [request setTag:3];
    [request startAsynchronous];
}
-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
    NSString *str=dic[@"key"];
    if ([str isEqualToString:@"success"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updatimageURL" object:nil];
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 定位
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (error.code==kCLErrorLocationUnknown) {
        NSLog(@"无法获取到当前位置信息");
    }else if (error.code==kCLErrorNetwork){
        NSLog(@"网络异常");
    }else if (error.code==kCLErrorDenied){
        NSLog(@"您的phone禁用获取位置服务");
    }
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误提示" message:@"获取位置信息失败"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
    CLLocation *currentLocation=newLocation;
    NSString *locstr1 = @"http://restapi.amap.com/v3/assistant/coordinate/convert?locations=";
    NSString *locstr2 = [NSString stringWithFormat:@"%f,%f",currentLocation.coordinate.longitude,currentLocation.coordinate.latitude];
    NSString *locstr3 = @"&coordsys=gps&output=json&key=b1ba3d04de3c8efdc866712f66033064";
    NSString *locstr4 = [NSString stringWithFormat:@"%@%@%@",locstr1,locstr2,locstr3];
    NSURL *url=[NSURL URLWithString:locstr4];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    NSString *poststr =@"";
    NSData *data=[poststr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        locationArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:locationArray waitUntilDone:YES];
        NSArray *strarray = [locationArray[@"locations"] componentsSeparatedByString:@","];
        _longitude = [strarray[0] doubleValue];
        _latitude = [strarray[1] doubleValue];
    }];
    [locationManager stopUpdatingLocation];
}
-(void)refreshData{
}
-(void)photoTapped{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择文件来源" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"本地相册",nil];
    [actionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://照相机
        {
            if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = NO;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }else{
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"没有找到摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
        }
            break;
            
        case 1://本地相簿
        {
            ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
            picker.maximumNumberOfSelection = 10;
            picker.assetsFilter = [ALAssetsFilter allPhotos];
            picker.showEmptyGroups=NO;
            picker.delegate=self;
            picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
                if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
                    NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                    return duration >= 5;
                } else {
                    return YES;
                }
            }];
            [self presentViewController:picker animated:YES completion:NULL];
        }
            break;
            
        default:
            break;
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    img = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    ImageCompression *ima = [[ImageCompression alloc]init];
    [ima imageByScalingToMaxSize:img];
    NSData *data;
    data = UIImageJPEGRepresentation(ima.newimage, 0.5);
    UIImage *image = [UIImage imageWithData:data];
    [self.imageArray addObject:image];
    [self addscrol];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    UIAlertView *alert;
    if (error)
    {
    }
    else
    {
    }
    [alert show];
}
#pragma mark - Assets Picker Delegate  选择图片结束后，把图片遍历一次，加到全局变量当中
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
    [self.scroll removeAllSubviews];
    for (int i=0; i<assets.count; i++) {
        ALAsset *index=[assets objectAtIndex:i];
        UIImage *image=[UIImage imageWithCGImage:index.defaultRepresentation.fullScreenImage];
        ImageCompression *ima = [[ImageCompression alloc]init];
        [ima imageByScalingToMaxSize:image];
        NSData *data = UIImageJPEGRepresentation(ima.newimage, 0.5);
        UIImage *image1 = [UIImage imageWithData:data];
        [self.imageArray addObject:image1];
    }
    [self addscrol];
}
-(void)addscrol{
    self.scroll.hidden = NO;
    CGFloat width=self.scroll.bounds.size.height;
    CGFloat height=self.scroll.bounds.size.height;
    for (int j=0; j<self.imageArray.count; j++) {
        UIImageView *imageView=[[UIImageView alloc] initWithImage:self.imageArray[j]];
        [imageView setFrame:CGRectMake(j*width+j*10, 0, width, height)];
        [self.scroll addSubview:imageView];
        imageView.userInteractionEnabled = YES;
        
        imageX = j*width+j*10 ;
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(imageView.frame.size.width -20, 0, 20, 20)];
        button.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"关闭.png"]];
        [button addTarget:self action:@selector(ImageDelete:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 1000 + j;
        [imageView addSubview:button];
        
    }
    ImageCompression *ima = [[ImageCompression alloc]init];
    [ima OriginImage:[UIImage imageNamed:@"addImage.png"] scaleToSize:CGSizeMake(width, height)];
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(imageX+width+10, 0, width, height)];
    image.backgroundColor = [UIColor colorWithPatternImage:ima.scaledImage];
    [self.scroll addSubview:image];
    image.userInteractionEnabled = YES;
    UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addImageClick)];
    [image addGestureRecognizer:gest];
    
    [self.scroll setBounces:NO];
    //设置水平方向的滚动条:
    [self.scroll setShowsHorizontalScrollIndicator:NO];
    //设置ScrollView的总体的宽度(关键)：
    [self.scroll setContentSize:CGSizeMake((self.imageArray.count +1) * (width+10), height)];
    //设置分页:
    [self.scroll setPagingEnabled:YES];
}
-(void)addImageClick{
    
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 10;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups=NO;
    picker.delegate=self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    [self presentViewController:picker animated:YES completion:NULL];

}


#pragma mark - 图片删除
-(void)ImageDelete:(UIButton *)button{
    
    [self.imageArray removeObjectAtIndex:(unsigned long)button.tag-1000];

    [self assetPickerController:nil didFinishPickingAssets:nil];
    
    if (self.imageArray.count == 0) {
        [self.scroll removeAllSubviews];
        [self.scroll setHidden:YES];
        [self.inputText becomeFirstResponder];
    }
    
}

- (void) changeContentViewPoint:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    keyboard = keyboardRect.size.height;
    //    CGFloat keyBoardEndY = value.CGRectValue.origin.y;  // 得到键盘弹出后的键盘视图所在y坐标
    NSNumber *duration = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(change:) object:nil];
    [thread start];
    //添加移动动画，使视图跟随键盘移动
    [UIView animateWithDuration:duration.doubleValue animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:[curve intValue]];
    }];
}
-(void)change:(id)sender
{
    //线程睡眠0.2秒以实现视图延迟上弹
    [NSThread sleepForTimeInterval:0.3];
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, -keyboard);
    //使视图使用这个变换
    self.inputView.transform = pTransform;
    
}
- (void)keyboardWillHide:(NSNotification *)notif {
    CGAffineTransform pTransform = CGAffineTransformMakeTranslation(0, 0);
    //使视图使用这个变换
    self.inputView.transform = pTransform;
    [UIView commitAnimations];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self hide];
}
-(void)hide{
    [self.inputView endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 拍照按钮
-(void)cameraClick{
    [self photoTapped];
}

#pragma mark - 语音按钮
-(void)VoiceClick{
    [self.view addSubview:self.recordView];
    self.QX.hidden = NO;
    self.recordView.hidden = NO;
    self.inputText.hidden = YES;
    self.speak.hidden = NO;
    self.scroll.hidden = YES;
    self.tag = 2;
    [self.inputText resignFirstResponder];
}

#pragma mark - 取消按钮
- (void)QuXiaoClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 发送按钮
- (void)FaSongClick {
    [self submit];
}
- (IBAction)QXAction:(id)sender {
    [self.recordView removeFromSuperview];
    self.QX.hidden = YES;
    self.inputText.hidden = NO;
    self.speak.hidden = YES;
    self.scroll.hidden = NO;
    self.tag=0;
    self.inputText.text = @"";
    [self.inputText becomeFirstResponder];
    
}
@end
